import express from "express";
import { spawn } from "child_process";
import path from "path";
import { fileURLToPath } from "url";
import cors from "cors";
import inquirer from "inquirer";
import chalk from "chalk";

// 获取当前目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
let address = null;
const ports = { main: 5320, blog: 5321, uiNavigate: 5322 };
const processes = {};

// 工具函数
const link = (url, text = url) => chalk.blue.underline(text);

// 获取服务器地址
async function promptAddress() {
    const answer = await inquirer.prompt([{
        type: "input",
        name: "address",
        default: "192.168.0.100",
        message: "请输入服务器地址：",
        validate: input => !!input.trim() || "地址不能为空"
    }]);
    address = answer.address;
}

// 启动子服务（兼容Windows和Unix系统）
function startProject(projectName, name, port) {
    return new Promise((resolve, reject) => {
        console.log(`🚀 启动 ${name} 服务...`);
        
        const isWindows = process.platform === 'win32';
        const cmd = isWindows ? 'npm.cmd' : 'npm';
        const args = ['run', 'dev', '--', '--host', address, '--port', port.toString()];
        
        const child = spawn(cmd, args, {
            cwd: path.join(__dirname, projectName),
            stdio: 'pipe', // 改为 pipe 才能捕获输出
            shell: true
        });

        let isResolved = false;

        // 监听正常输出（捕获启动完成消息）
        child.stdout.on('data', (data) => {
            const output = data.toString();
            console.log(`[${name}] ${output.trim()}`);
            
            // 检测 Vite/Webpack 启动完成消息
            if (!isResolved && (output.includes('Local:') || output.includes('ready in'))) {
                isResolved = true;
                resolve(child); // 返回子进程引用
            }
        });

        // 监听错误输出
        child.stderr.on('data', (data) => {
            const errOutput = data.toString();
            console.error(`[${name} ERROR] ${errOutput.trim()}`);
            if (!isResolved && errOutput.includes('ERROR')) {
                isResolved = true;
                reject(new Error(`${name} 启动失败: ${errOutput}`));
            }
        });

        // 进程退出处理
        child.on('close', (code) => {
            const msg = `${name} 已退出，代码 ${code}`;
            if (code !== 0) {
                console.error(`❌ ${msg}`);
                if (!isResolved) reject(new Error(msg));
            } else {
                console.log(`✅ ${msg}`);
            }
        });

        processes[projectName] = child;
    });
}

// Express中间件配置
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, "../web/Website")));
app.use("/pages", express.static(path.join(__dirname, "../web/pages")));
app.use("/public", express.static(path.join(__dirname, "../public")));

// 静态资源重定向
app.use((req, res, next) => {
    const host = req.headers.host || "";
    if(host.includes('localhost') || host.includes('127.0.0.1')) {
        return res.redirect(`http://${address}:${ports.main}${req.url}`);
    }
    next();
});

// API路由
const { router, databaseInitializationPromise } = await import('./api/dataRoutes.js');
app.use("/api", router);

// 健康检查
app.get("/health", (req, res) => {
    res.json({
        status: "running",
        services: {
            main: `http://${address}:${ports.main}`,
            blog: `http://${address}:${ports.blog}`,
            uiNavigate: `http://${address}:${ports.uiNavigate}`
        },
        currentIP: address
    });
});

// 启动所有服务
async function startAll() {
    try {
        await promptAddress();
        
        // 启动子服务
        await Promise.all([
            startProject("../web/Blog", "Blog", ports.blog),
            startProject("../web/UINavigate", "UINavigate", ports.uiNavigate)
        ]);
        
        // 启动主服务
        setTimeout(() => {
            app.listen(ports.main, "0.0.0.0", () => {
                console.log(chalk.green(`\n✅ 所有服务已启动！`));
                console.log(chalk.gray(`主服务: ${link(`http://${address}:${ports.main}`)}`));
                console.log(chalk.gray(`博客: ${link(`http://${address}:${ports.blog}`)}`));
                console.log(chalk.gray(`管理后台: ${link(`http://${address}:${ports.uiNavigate}`)}`));
            });
        }, 300);
    } catch (error) {
        console.error("❌ 启动失败:", error);
        process.exit(1);
    }
}

// 数据库初始化后启动
databaseInitializationPromise
    .then(startAll)
    .catch(err => {
        console.error('❌ 数据库初始化失败:', err);
        process.exit(1);
    });

// 优雅退出
process.on('SIGINT', () => {
    console.log('\n🛑 正在停止所有服务...');
    Object.values(processes).forEach(proc => proc.kill());
    setTimeout(() => process.exit(0), 500);
});